package system

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"jgyApi/server/global"
	"jgyApi/server/model/common/response"
	"jgyApi/server/model/system"
	systemReq "jgyApi/server/model/system/request"
	systemRes "jgyApi/server/model/system/response"
	"jgyApi/server/utils"
	"time"
)

type LauncherApi struct{}

func (l *LauncherApi) SetDefaultLauncher(c *gin.Context) {
	var s systemReq.CommonSn
	err := c.ShouldBind(&s)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(s, utils.SnVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	var rs utils.CacheResult
	rs = utils.GetRedisCacheField("sn", "value", s.Sn, "batch")
	if rs.Data == nil || rs.Data == "" {
		response.FailWithMessage("该设备没有设置批次", c)
		return
	}

	var dfLauncher system.DefaultLauncher
	where := fmt.Sprintf(" find_in_set(%s,batch_ids)", rs.Data)
	err = global.GVA_DB.Where(where).Where("del=?", -1).Preload("App").Order("id DESC").First(&dfLauncher).Error
	if err != nil {
		response.FailWithMessage("没有数据", c)
		return
	}

	var sn system.Sn
	err = global.GVA_DB.Where("value=?", s.Sn).First(&sn).Error

	if err != nil {
		response.FailWithMessage("sn不存在", c)
		return
	}

	var guidePageSet system.GuidePageSet
	where = fmt.Sprintf("find_in_set('%s',batch_ids) OR find_in_set('%d',child_admin)", *sn.Batch, sn.AdminID)
	err = global.GVA_DB.Where(where).Where("del=?", -1).First(&guidePageSet).Error

	var isNeed int64
	isNeed = -1
	if err == nil {
		isNeed = guidePageSet.IsNeed
	}

	response.OkWithDetailed(systemRes.SetDfLauncherResponse{
		AppID:      dfLauncher.AppID,
		AppPackage: dfLauncher.App.Bg,
		IsDefault:  dfLauncher.IsDefault,
		ID:         dfLauncher.ID,
		IsNeed:     isNeed,
	}, "success", c)
	return
}

func (l *LauncherApi) ReadNotice(c *gin.Context) {

	var rn systemReq.ReadNoticeReq
	err := c.ShouldBind(&rn)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(rn, utils.ReadNoticeVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	var sn system.Sn
	err = global.GVA_DB.Where("value = ?", rn.Sn).First(&sn).Error
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	var read system.SnReadNotice
	err = global.GVA_DB.Where(system.SnReadNotice{NoticeID: rn.NoticeID, Sn: rn.Sn}).Attrs(system.SnReadNotice{SnID: sn.ID, CreateTime: time.Now().Unix()}).FirstOrCreate(&read).Error
	if err != nil {
		response.FailWithMessage("更改状态失败", c)
		return
	}
	response.Ok(c)
}

func (l *LauncherApi) ConfirmNotice(c *gin.Context) {
	var rn systemReq.ReadNoticeReq
	err := c.ShouldBind(&rn)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(rn, utils.ReadNoticeVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	var notice system.SelfNotice
	err = global.GVA_DB.Where("id=?", rn.NoticeID).Where("del=?", -1).First(&notice).Error
	if err != nil {
		response.FailWithMessage("该通知不存在", c)
		return
	}
	if notice.FeedbackEndTime < time.Now().Unix() {
		response.FailWithMessage("已过确认通知截至时间", c)
		return
	}

	var readNotice system.SnReadNotice
	err = global.GVA_DB.Where("sn=?", rn.Sn).Where("notice_id=?", rn.NoticeID).First(&readNotice).Error
	if err != nil {
		response.FailWithMessage("该通知是未读状态", c)
		return
	}
	readNotice.IsConfirm = 1
	notice.ReadSnNum += 1
	global.GVA_DB.Save(readNotice)
	global.GVA_DB.Save(notice)
	response.Ok(c)
}

func (l *LauncherApi) GetSelfNotice(c *gin.Context) {
	var s systemReq.CommonSn
	err := c.ShouldBind(&s)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(s, utils.SnVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	var sn system.Sn
	err = global.GVA_DB.Where("value = ?", s.Sn).First(&sn).Error
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	where := fmt.Sprintf("find_in_set('%s',batch_ids) OR find_in_set('%d',child_admin)", *sn.Batch, sn.AdminID)
	var noticeRes []systemRes.NoticeResponse
	se := "noe.id,noe.name,noe.content,noe.file_list,noe.is_need,noe.feedback_end_time,noe.feedback_type,IF(is_confirm IS NULL,-1,1) AS is_read,IF(is_confirm IS NULL,-1,is_confirm) AS is_confirm"
	leftJoin := fmt.Sprintf("LEFT JOIN sn_read_notice as sr ON noe.id=sr.notice_id AND sr.sn='%s'", sn.Value)
	global.GVA_DB.Table("self_notice as noe").Select(se).Joins(leftJoin).Where(where).Where("del=?", -1).Find(&noticeRes)
	response.OkWithData(noticeRes, c)
}

func (l *LauncherApi) GetHomework(c *gin.Context) {
	var s systemReq.CommonSn
	err := c.ShouldBind(&s)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(s, utils.SnVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	var rs utils.CacheResult
	rs = utils.GetRedisCacheField("sn", "value", s.Sn, "batch")
	if rs.Data == nil || rs.Data == "" {
		response.FailWithMessage("该设备没有设置批次", c)
		return
	}
	var homework []system.Homework
	where := fmt.Sprintf(" find_in_set(%s,batch_ids)", rs.Data)
	err = global.GVA_DB.Where(where).Preload("Questions").Find(&homework).Error
	if err != nil {
		response.FailWithMessage("没有数据", c)
		return
	}
	response.OkWithData(homework, c)

}

func (l *LauncherApi) GetStudentAnswer(c *gin.Context) {

	var req systemReq.StudentAnswerReq
	err := c.ShouldBind(&req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(req, utils.StudentAnswerVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	//校验数据
	var sn system.Sn
	err = global.GVA_DB.Model(&system.Sn{}).Where("value=?", req.Sn).First(&sn).Error
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	var homework system.Homework
	err = global.GVA_DB.Model(&system.Homework{}).Where("id=?", req.HomeworkID).Where("del=?", -1).First(&homework).Error
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if homework.DeadlineTime < time.Now().Unix() {
		response.FailWithMessage("已过作业提交截至时间", c)
		return
	}
	var snSubmit system.SnSubmitHomework
	err = global.GVA_DB.Where("homework_id=?", homework.ID).Where("sn=?", req.Sn).First(&snSubmit).Error

	if err == nil {
		response.FailWithMessage("已提交过,请勿重复提交", c)
		return
	}

	//数据处理
	type answer struct {
		QuestionID    int64  `json:"question_id"`
		StudentAnswer string `json:"studentAnswer"`
		Grade         int64  `json:"grade"`
		TeacherJudge  int64  `json:"teacherJudge"`
	}
	var answerArr []answer

	switch homework.Type {
	case 1:
		if req.Answer == "" {
			response.FailWithMessage("答案为空", c)
			return
		}
		err = json.Unmarshal([]byte(req.Answer), &answerArr)
		if err != nil {
			response.FailWithMessage("答案解析失败", c)
			return
		}
		snSubmit.Sn = req.Sn
		aw, _ := json.Marshal(answerArr)
		snSubmit.Answer = string(aw)
		snSubmit.HomeworkID = homework.ID
		snSubmit.CreateTime = time.Now().Unix()
		snSubmit.AnswerFile = ""
		snSubmit.JudgeFile = ""

	case 2:
		if req.AnswerFile == "" {
			response.FailWithMessage("答案文件为空", c)
			return
		}
		snSubmit.Sn = req.Sn
		snSubmit.Answer = ""
		snSubmit.HomeworkID = homework.ID
		snSubmit.CreateTime = time.Now().Unix()
		snSubmit.AnswerFile = ""
		snSubmit.JudgeFile = ""
	}
	global.GVA_DB.Save(&snSubmit)
	homework.SubmitSnNum += 1
	global.GVA_DB.Save(&homework)
	response.OkWithData(answerArr, c)
	return
}
